package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;

public class AccessFilter extends ZuulFilter {
    //设置过滤器的类型：pre,routing,post,error
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;//前置过滤器
    }

    //设置过滤器的顺序号
    @Override
    public int filterOrder() {
        return 6;
    }

    //对客户端的当前请求进行判断
    //针对当前请求，是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        //如果调用item-service，要执行过滤代码判断权限
        //否则不执行过滤代码

        //获取调用的服务id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        //判断是否为item-service
        //equequalsIgnoreCase 忽略大小写比较
        return "item-service".equalsIgnoreCase(serviceId);

    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/23552dsf?token=23kdjgs
        //获取request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //接收token参数

        String token = request.getParameter("token");
        //如果没有收到token参数,认为用户没登陆，阻止其调用
        if (StringUtils.isBlank(token)) {
            //阻止继续调用
            ctx.setSendZuulResponse(false);//是否向后台发送响应

            //设置向客户端发送的响应
            ctx.addZuulResponseHeader("Content-Type", "application/json");
            //JsonResult - {code:401,msg:"not login",data:null}
            ctx.setResponseBody(JsonResult.err().msg("not login").toString());
        }
        return null;//在当前zuul版本中，这个返回值没有任何作用
    }
}
